#include "CImage.h"
#include "formats/CJpegLoader.h"
#include "formats/CDevilLoader.h"
#include "CView.h"
#include "SSequencer.h"
#include "SRenderer.h"

//----------------------------------------------
CImage::CImage() :
m_iWidth(0),
m_iHeight(0),
m_pBuffer(NULL),
m_iBufferSize(0),
m_pDeviceData(NULL)
{
}

//----------------------------------------------
CImage::~CImage()
{
	delete[] m_pBuffer;
}

//----------------------------------------------
bool CImage::load (const xstring& sPath, EImageType /*eType*/)
{
	if (m_eStatus == E_STATUS_LOADED)
		return true;
	if (m_eStatus == E_STATUS_LOADING || m_eStatus == E_STATUS_UNLOADING)
		return false;

	bool bLoaded = false;
	m_eStatus = E_STATUS_LOADING;

	/*
	switch (eType)
	{
	case E_JPEG:	bLoaded = CJpegLoader::load(*this, sPath); break;
	default:		break;
	}*/

	bLoaded = CDevilLoader::load(*this, sPath);


	if (bLoaded)
	{
		m_eStatus = E_STATUS_LOADED;
		return true;
	}
	else
	{
		m_eStatus = E_STATUS_NONE;
		return false;
	}
}

//----------------------------------------------
void CImage::unload()
{
	if (m_eStatus == E_STATUS_LOADED)
	{
		m_eStatus = E_STATUS_UNLOADING;
		delete[] m_pBuffer;
		m_pBuffer		= NULL;
		m_iBufferSize	= 0;
		m_iWidth		= 0;
		m_iHeight		= 0;

		CResource::unload();
	}
	m_eStatus = E_STATUS_NONE;
}

//----------------------------------------------
EImageType CImage::getImageType(const xstring& sPath)
{
	xstring sExtension = sPath.substr(sPath.rfind(CSTR(".")) + 1);
	if (sExtension == CSTR("jpg") || sExtension == CSTR("jpeg"))
		return E_JPEG;
	return E_NOT_A_VALID_IMAGE_TYPE;
}

//----------------------------------------------
void CImage::createBuffer(int iWidth, int iHeight)
{
	m_iWidth = iWidth;
	m_iHeight = iHeight;
	m_iBufferSize = m_iWidth * m_iHeight * 3;
	delete[] m_pBuffer;
	m_pBuffer = new byte[m_iBufferSize];
}

//----------------------------------------------
void CImage::releaseBuffer()
{
	delete[] m_pBuffer;
	m_pBuffer = NULL;
}

//----------------------------------------------
CImagePool::CImagePool()
{
}

//----------------------------------------------
bool CImagePool::loadNewImage(CFileInfo& oInfo)
{
	bool bLoaded = oInfo.m_oImage.load(oInfo.m_oPath.c_str(), oInfo.m_eImageType);
	if (bLoaded)
	{
		bLoaded = SRenderer::instance()->loadTexture(oInfo.m_oImage);
		if (bLoaded)
		{
			if (m_oImages.size() > 0)
			{
				CImage* pOld = m_oImages.back();
				if (pOld != NULL)
					pOld->unload();
			}
			m_oImages.push(&oInfo.m_oImage);
			return true;
		}
		else
		{
			oInfo.m_oImage.unload();
		}
	}

	return false;
}